﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsStateService.Data;
using WindowsStateService.Manager;

namespace WindowsStateService
{
    public static class ConfigFileHelper
    {
        private static DateTime last_write_time;
        private static string properties_file_path;
        private static PropertiesConfig _instance;
        public static PropertiesConfig Instance
        {
            get 
            {
                FileInfo info = new FileInfo(properties_file_path);
                if(info.LastWriteTime.Subtract(last_write_time).TotalSeconds > 0)
                {
                    Read();
                    //CommonPath.CreateSerialPortConfigFile();
                    //SerialPortService.Instance.SaveSerialPortInfo();
                }
                return _instance; 
            }
        }

        public static void Initialize()
        {
            properties_file_path = Get();
            Read();
            FileInfo info = new FileInfo(properties_file_path);
            last_write_time = info.LastWriteTime;
        }

        public static void Read()
        {
            using (FileStream fs = new FileStream(properties_file_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader reader = new StreamReader(fs))
                {
                    string line = reader.ReadLine();
                    if (!string.IsNullOrWhiteSpace(line))
                    {
                        _instance = JsonConvert.DeserializeObject<PropertiesConfig>(line);
                    }
                }
            }
        }

        private static string Get()
        {
           string specFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.Create);
            string configDir = specFolder + Path.DirectorySeparatorChar + "WatchMe" + Path.DirectorySeparatorChar + CommonPath.GetAssemblyVersion()
              + Path.DirectorySeparatorChar + "WatchMeProperties.config";
            return configDir;
        }
    }
}
